import { Body, Controller, Delete, Get, HttpException, HttpStatus, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { LantUtil } from '../../../../utils/lant.util';
import { LogAppender } from '../../constants/log.constant';
import { GetUserActivityLogAdminReqDto } from '../../dtos/user-activity/admin/get-user-activity-log.admin.req.dto';
import { GetUserActivityLogAdminResDto } from '../../dtos/user-activity/admin/get-user-activity-log.admin.res.dto';
import { LogService } from '../../services/log.service';
import { UserActivityLogService } from '../../services/user-activity-log.service';
import { AuthGuard } from '@nestjs/passport';
import { Authorities } from '../../../../decorators/authorities.decorator';
import { AuthoritiesGuard } from '../../../../guards/authorities.guard';
import { Guard } from '../../../guard/constants/guard.constant';
import { IdListReqDto } from '../../../common/dtos/id-list.req.dto';
import { CountResDto } from '../../../common/dtos/count.res.dto';

@ApiBearerAuth()
@ApiTags('user activity logs')
@Controller('admin/user_activity_logs')
export class UserActivityLogAdminController {
  constructor(private readonly userActivityLogService: UserActivityLogService, private readonly logService: LogService, private readonly lantUtil: LantUtil) {}

  @ApiOperation({ summary: '批量删除日志' })
  @ApiOkResponse({ description: '返回删除结果', type: CountResDto })
  @Authorities(Guard.UserActivityLogManage)
  @UseGuards(AuthGuard(), AuthoritiesGuard)
  @Delete()
  async deleteAll(@Body() body: IdListReqDto): Promise<CountResDto> {
    try {
      const deleteResult = await this.userActivityLogService.deleteAll(body.id_list);

      return { count: deleteResult.affected };
    } catch (error) {
      if (error instanceof HttpException) throw error;
      this.logService.fatal(LogAppender.log, `Cannot delete user activity log list by ${JSON.stringify(body)}, the error is ${error}`, this.lantUtil.parseError(error));
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @ApiOperation({ summary: '获取用户活动日志列表' })
  @ApiOkResponse({ description: '用户活动日志列表', type: GetUserActivityLogAdminResDto })
  @Authorities(Guard.UserActivityLogManage, Guard.UserActivityLogView)
  @UseGuards(AuthGuard(), AuthoritiesGuard)
  @Get()
  async getAll(@Query() query: GetUserActivityLogAdminReqDto): Promise<GetUserActivityLogAdminResDto> {
    try {
      const [logList, count] = await this.userActivityLogService.findAndPaging(
        query.page_index,
        query.page_size,
        query.order_by,
        query.sort_type,
        query.start,
        query.end,
        query.level,
        query.method,
        query.url,
        query.request_message,
        query.keyword
      );

      return {
        total_count: count,
        data: logList?.map(log => {
          return {
            id: log.id,
            level: log.level,
            method: log.method,
            user_uuid: log.userUuid,
            ip: log.ip,
            url: log.url,
            request_message: log.requestMessage,
            response_code: log.responseCode,
            response_message: log.responseMessage,
            interval: log.interval,
            created_at: log.createdAt
          };
        })
      };
    } catch (error) {
      if (error instanceof HttpException) throw error;
      this.logService.fatal(LogAppender.log, `Cannot get user activity log list by ${JSON.stringify(query)}, the error is ${error}`, this.lantUtil.parseError(error));
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
